<template>
  <div :class="classObj" class="app-wrapper">
    <div v-if="device==='mobile'&&sidebar.opened" class="drawer-bg" @click="handleClickOutside"/>
    <sidebar class="sidebar-container" :routes="userRoutes" :active-menu="activeMenu"/>
    <div class="main-container">
      <div :class="{'fixed-header':fixedHeader}">
        <nav-bar/>
      </div>
      <app-main :routes="userRoutes" :route-list="userPermissionRoutes" @activeMenu="activeMenuChange"/>
    </div>
    <div v-if="true===hasNewVersion" class="update-remind-div">
      <div class="update-remind-content-div">
        <div><i class="el-icon-info icon"/></div>
        <div v-if="true===osIsWindows">当前有新版本，请按Ctrl+F5强制刷新</div>
        <div v-if="false===osIsWindows">当前有新版本，请按Command+Shift+R强制刷新</div>
        <el-button type="primary" class="confirm-version-update-remind-button" @click="confirmVersionUpdateRemind">
          稍后处理
        </el-button>
      </div>
    </div>
    <div v-if="true===showChangeAccountRemind" class="change-account-remind-div">
      <div class="change-account-remind-content-div">
        <div><i class="el-icon-info icon"/></div>
        <div v-if="true===hasSessionToken">
          当前登录账号已被其他账号覆盖，如果需要同时登录不同账号，请使用其他浏览器登录
        </div>
        <div v-if="false===hasSessionToken">
          <div>登录状态已失效</div>
          <el-button type="primary" @click="goToLogin">重新登录</el-button>
        </div>
      </div>
    </div>
    <version ref="version"/>
  </div>
</template>

<script>
import {AppMain, NavBar, Sidebar} from './components'
import ResizeMixin from './mixin/ResizeHandler'
import {mapGetters} from 'vuex'
import Version from '@/components/version/version.vue'
import {getToken} from "@/utils/auth";
import myLocalStorage from "@/utils/localStorage";

let checkVersionInterval

export default {
  name: 'HomePage',
  watch: {
    '$store.state.routerMessage': function (param) {
      if ('hasNewVersion' === param.action) {
        this.hasNewVersion = true;
      }
    }
  },
  components: {
    NavBar,
    Sidebar,
    AppMain,
    Version
  },
  mixins: [ResizeMixin],
  data() {
    return {
      hasNewVersion: false,
      versionCode: 0,
      osIsWindows: true,
      showChangeAccountRemind: false,
      hasSessionToken: false,
      loginAccount: '',
      activeMenu: ''
    }
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'routeList'
    ]),
    userPermissionRoutes() {
      return this.generateRoutes(this.userInfo.permissionList)
    },
    sidebar() {
      return this.$store.state.app.sidebar
    },
    device() {
      return this.$store.state.app.device
    },
    fixedHeader() {
      return this.$store.state.settings.fixedHeader
    },
    routes() {
      return this.$router.options.routes
    },
    userRoutes() {
      return this.assembleTree({
        data: this.userPermissionRoutes, // this.routeList
        parent: 'parentPermissionCode',
        id: 'permissionCode',
        child: 'children'
      })
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened,
        withoutAnimation: this.sidebar.withoutAnimation,
        mobile: this.device === 'mobile'
      }
    }
  },
  created() {
    //
    this.osIsWindows = navigator.userAgent.indexOf('Windows') > -1
    // 每隔一分钟检查新版本
    setTimeout(() => {
      this.versionCode = this.$refs.version.versionCode
    }, 500)
    checkVersionInterval = window.setInterval(() => {
      this.$api.getVersion({
        appSort: 5,
        version: this.versionCode
      }, {showLoading: false}).then(res => {
        if (res.versionCode > this.versionCode) {
          this.hasNewVersion = true
        }
      }, _ => {
      })
    }, 600_000)
    this.$store.dispatch('static/setOrganizationTypeList')
    this.loginAccount = myLocalStorage.getJsonItem('userInfo') == null ? '' : myLocalStorage.getJsonItem('userInfo')['loginAccount']
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'visible') {
        // 判断是否有切换账号
        const sessionToken = getToken();
        const loginAccount = myLocalStorage.getJsonItem('userInfo') == null ? '' : myLocalStorage.getJsonItem('userInfo')['loginAccount']
        if (loginAccount !== this.loginAccount || undefined === sessionToken || '' === sessionToken) {
          this.showChangeAccountRemind = true;
          this.hasSessionToken = undefined !== sessionToken && '' !== sessionToken;
        }
      } else {
        // 处理页面不可见的情况
      }
    });
  },
  methods: {
    goToLogin() {
      this.$router.push({
        path: '/login'
      })
    },
    confirmVersionUpdateRemind() {
      this.hasNewVersion = false
      window.clearInterval(checkVersionInterval)
    },
    handleClickOutside() {
      this.$store.dispatch('app/closeSideBar', {withoutAnimation: false})
    },
    generateRoutes(routeList) {
      // 设置排序序号
      for (let i = 0; i < routeList.length; i++) {
        routeList[i].reorder = i
      }
      // 根据用户权限删除无效路由
      const newList = []
      let j
      for (j = 0; j < routeList.length; j++) {
        for (let i = 0; i < this.routes.length; i++) {
          if (this.routes[i].meta === undefined) {
            continue
          }
          if (this.routes[i].meta.permissionCode === routeList[j].permissionCode) {
            const {
              meta = {
                title: this.routes[i].permissionName,
                icon: ''
              }, path, hidden = false, unique = false, disableDelete = false, name = this.routes[i].permissionName
            } = this.routes[i]
            this.routes[i] = {
              permissionName: this.routes[i].meta.title,
              permissionCode: this.routes[i].meta.permissionCode,
              parentPermissionCode: routeList[j].parentPermissionCode,
              permissionType: routeList[j].permissionType,
              reorder: routeList[j].reorder,
              meta, hidden, unique, name, path, disableDelete,
            }
            if (!this.routes[i].children) {
              this.routes[i].children = []
            }
            newList.splice(j, 0, this.routes[i])
          }
        }
      }
      // 重新排序
      newList.sort(function (a, b) {
        return a.reorder > b.reorder ? 1 : -1
      })
      return newList
      // for (let routeIndex = this.routes.length - 1; routeIndex >= 0; routeIndex--) {
      //     let routeItem = this.routes[routeIndex];
      //     const localRouteIndex = routeList.findIndex(res => routeItem.meta && routeItem.meta.permissionCode === res.permissionCode);
      //     //   const localRouteIndex = this.routes.findIndex(res => res.name === routeItem.permissionName)
      //     if (localRouteIndex >= 0) {
      //         const {
      //             meta = {
      //                 title: routeItem.permissionName,
      //                 icon: ''
      //             }, path, hidden = false, unique = false, disableDelete = false, name = routeItem.permissionName
      //         } = routeList[localRouteIndex];
      //         routeItem = {...routeItem, meta, hidden, unique, name, path, disableDelete}
      //     }
      //     if (!routeItem.children) {
      //         routeItem.children = []
      //     }
      //     this.routes[routeIndex] = routeItem
      // }
      // console.log('routeList:', routeList);
      // return routeList
    },
    assembleTree(params) {
      const options = {
        data: params.data,
        parent: params.parent,
        id: params.id,
        child: params.child
      }
      return options.data.filter((parent) => {
        const item = options.data.filter((child) => {
          if (child.permissionType !== 1) {
            return
          }
          return parent[options.id] === child[options.parent] && child['meta']
        })
        if (item.length > 0) {
          parent[options.child] = item
        }
        return parent[options.parent] === 0 || parent[options.parent] === ''
      })
    },
    activeMenuChange(event) {
      this.activeMenu = event
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
@import "~@/styles/variables.scss";

.app-wrapper {
  @include clearfix;
  position: relative;
  height: 100%;
  width: 100%;

  &.mobile.openSidebar {
    position: fixed;
    top: 0;
  }
}

.drawer-bg {
  background: #000;
  opacity: 0.3;
  width: 100%;
  top: 0;
  height: 100%;
  position: absolute;
  z-index: 999;
}

.fixed-header {
  position: fixed;
  top: 0;
  right: 0;
  z-index: 9;
  width: calc(100% - #{$sideBarWidth});
  transition: width 0.28s;
}

.hideSidebar .fixed-header {
  width: calc(100% - 54px);
}

.mobile .fixed-header {
  width: 100%;
}

.update-remind-div {
  z-index: 999999;
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;

  .update-remind-content-div {
    width: 50vw;
    height: 50vh;
    background-color: #fff;
    border-radius: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    font-size: 24px;
    color: var(--color-red);
    line-height: 250%;
    text-align: center;

    .icon {
      font-size: 150px;
      color: #999;
    }
  }

  .confirm-version-update-remind-button {
    margin-top: 50px;
    width: 200px;
  }
}

.change-account-remind-div {
  position: fixed;
  z-index: 999999;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;

  .change-account-remind-content-div {
    width: 50vw;
    height: 50vh;
    background-color: #fff;
    border-radius: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    font-size: 22px;
    color: var(--color-red);
    line-height: 250%;
    text-align: center;

    .icon {
      font-size: 150px;
      color: #999;
    }
  }
}
</style>
